package main

import (
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"log"
	"net/http"
)

type UaaPublickey struct {
	Alg   string `json:alg`
	Value string `json:"value"`
}

func main() {
	token := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJleHAiOjE1ODcwMDYwNTEsImlhdCI6MTU4NzAwNTc1MSwiYXV0aG9yaXRpZXMiOlsic3lzOnBlcm1pc3Npb246Y29kZXMiLCJzeXM6ZGVwYXJ0bWVudDp1cGRhdGUiLCJzeXN0ZW06bWFuYWdlbWVudCIsInN5czpkZXBhcnRtZW50OnBhZ2UiLCJzeXM6cm9sZTptYW5hZ2VtZW50Iiwic3lzOnBlcm1pc3Npb246YWRkIiwiYWRtaW4iLCJzeXM6cm9sZTpwYWdlIiwic3lzOnVzZXI6YWRkIiwic3lzOmRlcGFydG1lbnQ6ZGVsZXRlIiwic3lzOnBlcm1pc3Npb246cGFnZSIsInN5czpwZXJtaXNzaW9uOm1hbmFnZW1lbnQiLCJzeXM6dXNlcjpkZWxldGUiLCJzeXM6ZGVwYXJ0bWVudDptYW5hZ2VtZW50Iiwic3lzOnVzZXI6cGFnZSIsInN5czp1c2VyOnVwZGF0ZSIsInN5czp1c2VyOnVwZGF0ZTpoZWFkIiwic3lzOnVzZXI6dXBkYXRlOnBhc3N3b3JkIiwic3lzOnJvbGU6YWRkIiwic3lzOnBlcm1pc3Npb246bWVudTp0cmVlIiwic3lzOmRlcGFydG1lbnQ6aW5mbyIsInN5czpwZXJtaXNzaW9uOmFsbDptZW51Omxpc3QiLCJzeXM6cGVybWlzc2lvbjppbmZvIiwic3lzOnJvbGU6aW5mbyIsInN5czpwZXJtaXNzaW9uOmFsbDptZW51OnRyZWUiLCJzeXM6cGVybWlzc2lvbjp1cGRhdGUiLCJzeXM6cGVybWlzc2lvbjptZW51Omxpc3QiLCJzeXM6cm9sZTp1cGRhdGUiLCJzeXM6dXNlcjppbmZvIiwic3lzOnVzZXI6bWFuYWdlbWVudCIsInN5czpyb2xlOmRlbGV0ZSIsInN5czpwZXJtaXNzaW9uOmRlbGV0ZSJdLCJqdGkiOiJmYTljODlmMS1iYzYxLTQwYmMtYTFmMi1jYTVjMzQ2NjQyM2QiLCJjbGllbnRfaWQiOiJ3ZWJfYXBwIn0.SkWGUeMsUBy55HdZIKPD4Me1AqNqxJpn0dk0awcMXNQetQOX-5g8JibjXYra9GWYOtXJRlyukcSmBXxjBfVpNUl20c86urwFUWQKIVyiJ-mVFzPalL_lM3gvm0tewfuP5Pvi7MtM4uS8UiTqTrB5XcUsPqF4o1UuXio-pL4OiWwDb85qKu0ItsZb8bDzOEdOWP4-huFc1nuS9KXFI8amuqLqNVpQhtkoRdv_t0MQ5MVVI2r5Z0StsZHdmY7He4FYaAD_Hld37yvwghV4cEnqqP7flcuQBD1XzIcJdwdrjf9zJj5u35u4w2NOSZ2anRwqQWF3dn4Raxf5YQhl7IXOaw"
	if jwttoken, err := jwt.Parse(token, GetPublicKey); err == nil {
		jsonJwt, _ := json.MarshalIndent(jwttoken, "", "  ")
		log.Printf("jwt ==== %s", jsonJwt)
	} else {
		log.Printf("%v", err)
	}
}

func GetPublicKey(token *jwt.Token) (i interface{}, e error) {
	request := http.DefaultClient
	var resp *http.Response
	var err error
	if resp, err = request.Get("http://localhost:9999/oauth/token_key"); err != nil {
		log.Fatalf("error %s", err)
	}

	var key UaaPublickey
	json.NewDecoder(resp.Body).Decode(&key)
	defer resp.Body.Close()
	log.Printf("publickey value %v", key.Value)
	log.Printf("publickey alg %v", key.Alg)
	keyDERBlock, _ := pem.Decode([]byte(key.Value))
	if keyDERBlock == nil {
		log.Fatal("keyDERBlock error ")
	}
	log.Printf("%s", keyDERBlock.Type)
	if publickey, err := x509.ParsePKIXPublicKey(keyDERBlock.Bytes); err == nil {
		return publickey, nil
	} else {
		return nil, errors.New("public key error")
	}
}
